package com.xmmj.baselibrary.utils

import android.widget.EditText
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Rect
import android.view.inputmethod.InputMethodManager

/**
 * 窗口显示工具类
 */
object Display {
    /**
     * 获取屏幕宽度
     *
     * @param context 上下文
     */
    fun getScreenW(context: Context): Int {
        val dm = context.resources.displayMetrics
        return dm.widthPixels
    }

    /**
     * 获取屏幕高度
     *
     * @param context 上下文
     */
    fun getScreenH(context: Context): Int {
        val dm = context.resources.displayMetrics
        return dm.heightPixels
    }

    /**
     * 显示输入法
     *
     * @param context 上下文
     */
    fun showKeyboard(context: Context) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    /**
     * 隐藏输入法
     *
     * @param editText 编辑框
     */
    fun hideKeyboard(editText: EditText) {
        val imm =
            editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

    /**
     * 截屏
     *
     * @param activity      上下文
     * @param withStatusBar 是否包含状态栏
     */
    fun screenShot(activity: Activity, withStatusBar: Boolean): Bitmap {
        val view = activity.window.decorView
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache()
        val bmp = view.drawingCache

        var statusBarHeight = 0
        if (withStatusBar) {
            val frame = Rect()
            activity.window.decorView.getWindowVisibleDisplayFrame(frame)
            statusBarHeight = frame.top
        }

        val width = getScreenW(activity)
        val height = getScreenH(activity)
        val bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight)
        view.destroyDrawingCache()
        return bp
    }
}